<template>
  <div class="add-agreement-dialog-view">

    <el-dialog
            v-model="dialogShow"
            :close-on-click-modal="false"
            width="800px"
            title="新建区域招商要素"
            @closed="close"
            size="small"
    >

      <el-form
              :rules="rule"
              ref="refForm"
              :model="formData"
              label-width="120px"
              class="demo-ruleForm"
              size="small"
      >

        <el-row>

          <el-col :span="12">
            <el-form-item
                    label="负责营销职员"
                    prop="headId"
                    style="width: 100%"
            >
              <el-select
                      v-model="formData.headId"
                      style="width: 100%"
                      placeholder="请选择营销职员"
                      @change="headChange"
              >
                <el-option
                        v-for="item in headOptions"
                        :key="item.id"
                        :label="item.realName"
                        :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                    label="关联营销任务"
                    style="width: 100%"
            >
              <!--              <seller-task ref="sellerTaskRef" :headId="formData.headId" @confirm="sellerConfirm" plan-type="2" is-position>-->
              <!--                <el-select v-model="formData.planName" :disabled="formData.headId == 0" clearable-->
              <!--                           placeholder="请选择关联营销任务" style="width: 100%" @clear="sellerClear" @focus="sellerFocus">-->
              <!--                  <template #empty />-->
              <!--                </el-select>-->
              <!--              </seller-task>-->

              <el-input
                      ref="refInput"
                      v-model="formData.saleTaskNo"
                      placeholder="请输入营销任务"
                      clearable
                      @clear="taskClear"
                      @blur="taskBlur"
                      @focus="taskFocus"
              />

            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                    label="代理名称"
                    prop="agentName"
                    style="width: 100%"
            >
              <el-autocomplete
                      v-model="formData.agentName"
                      style="width: 100%"
                      placeholder="请输入代理商名称"
                      @blur="agentBlur"
                      :fetch-suggestions="querySearchAsyncAgent"
                      @select="handleSelectAgent"
              >
                <template #default="{ item }">
                  <div class="distributeName" v-if="item.agentType == 'agent'">{{ item.agentName }}</div>
                  <div class="distributeName" v-else>{{ item.userName }}</div>
                </template>
              </el-autocomplete>

            </el-form-item>
          </el-col>

          <el-col :span="12">

            <el-form-item v-if="isNot" label="未找到代理商">
              <el-button type="text" @click="onCreate" style="margin: 0 10px">创建代理商</el-button>

            </el-form-item>

          </el-col>

          <el-col :span="12">
            <el-form-item
                    label="通用名"
                    prop="productPopularName"
                    style="width: 100%"
            >

              <product-popover
                      :searchs="formData.productPopularName"
                      :disabled="disabled || isPlan"
                      @confirm="productConfirm"
                      type="2"
              >
                <el-input
                        v-model="formData.productPopularName"
                        :disabled="isPlan"
                        placeholder="请输入产品名称"
                />
              </product-popover>

            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                    label="商品名"
                    style="width: 100%"
            >
              <el-input
                      v-model="formData.productName"
                      placeholder="请输入商品名"
                      disabled
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                    label="包装规格"
                    style="width: 100%"
            >
              <el-input
                      v-model="formData.packSpecs"
                      placeholder="请选择包装规格"
                      disabled
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                    label="生产厂家"
                    style="width: 100%"
            >
              <el-input
                      v-model="formData.producer"
                      placeholder="请选择生产厂家"
                      disabled
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                    label="可营销终端"
                    prop="terminalType"
                    style="width: 100%"
            >
              <el-select
                      style="width: 100%"
                      v-model="formData.terminalType"
                      @change="typeChange"
                      placeholder="请选择营销终端"
              >
                <el-option
                        v-for="item in appOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                    label="代理地区"
                    prop="areas"
                    style="width: 100%"
            >
              <el-cascader
                      style="width: 100%"
                      :popper-append-to-body="false"
                      ref="cascader"
                      v-model="formData.areas"
                      :options="citys"
                      :props="props1"
                      placeholder="请选择地区"
                      @change="areaChange"
                      collapse-tags
                      clearable
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                    label="交易价"
                    prop="tradePrice"
            >

              <price-input
                      v-model:data="formData.tradePrice"
                      placeholder="请输入交易价"
                      is-unit
                      :unitStr="formData.sellUnit ? '元/' + getLabel('sell_unit',formData.sellUnit) : ''"
                      @blur="onBlur"
              ></price-input>
              <template v-if="isUnde">
                <div>
                  <span style="color: #E6A23C">输入的交易价低于该地区产品底价{{guidingPrice}}元/{{getLabel('sell_unit',formData.sellUnit)}}</span>
                </div>

              </template>

            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                    style="width: 100%"
                    label="代理期限至"
                    prop="agentEndTime"
            >
              <date-picker
                      style="width: 100%"
                      v-model:date="formData.agentEndTime"
                      :disabled-date="disabledDate"
                      placeholder="请选择期限"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                    label="最低销量"
                    prop="minSale"
            >
              <div v-if="type == 1">
                <span v-if="formData.minSale && formData.isIncrease == 1">{{formData.minSale}}{{getLabel('sell_unit',formData.sellUnit)}}/年</span>
                <span v-else-if="formData.minSale">首年{{formData.minSale}}{{getLabel('sell_unit',formData.sellUnit)}},每年递增{{formData.increaseNum}}%</span>
                <el-button
                        style="margin-left: 10px"
                        type="text"
                        @click="editNum"
                >设置</el-button>
              </div>

              <el-input
                      v-else
                      v-model.number="formData.minSale"
                      placeholder="请输入最低销量"
              >
                <template #append>
                  <span
                          style="margin-right: 10px"
                          v-if="formData.sellUnit"
                  >{{getLabel('sell_unit',formData.sellUnit)}}/</span>
                  <el-select
                          v-model="formData.minSaleUnit"
                          placeholder=""
                          style="width: 80px"
                  >
                    <el-option
                            v-for="item in unitOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-input>

            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
                    label="销量保证金"
                    v-if="formData.agentAttribute == 1"
                    prop="minSalePromise"
            >
              <el-input
                      v-model.number="formData.minSalePromise"
                      placeholder="请输入销量保证金"
              >
                <template #append>
                  <span>元</span>
                </template>
              </el-input>

            </el-form-item>
            <el-form-item
                    label="销量保证金"
                    v-else
            >
              <el-input
                      v-model.number="formData.minSalePromise"
                      placeholder="请输入销量保证金"
                      clearable
              >
                <template #append>
                  <span>元</span>
                </template>
              </el-input>

            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item
                    label="其他约定"
                    style="width: 100%"
            >
              <el-input
                      v-model="formData.remark"
                      placeholder="请输入其他约定"
              ></el-input>
            </el-form-item>
          </el-col>

        </el-row>

      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
                  class="border-btn"
                  size="small"
                  @click="close"
          >取消</el-button>
          <el-button
                  class="main-btn"
                  size="small"
                  type="primary"
                  @click="confirm"
          >提交审核</el-button>
        </div>
      </template>
    </el-dialog>

    <sellNumDialog
            ref="sellNumDialog"
            :datas="formData"
    />

    <fromDialog ref="fromDialog"/>

    <chanceTaskDialog ref="chanceTask" :head-id="formData.headId" :task-type="1" @confirm="taskConfirm"/>
  </div>
</template>

<script>

  import {crmStore} from '../../../store'
  import {defineAsyncComponent,nextTick,watch, defineComponent, getCurrentInstance, inject, onMounted, reactive, toRefs,} from 'vue'

  export default defineComponent({
    name: 'AddAgreementDialog',
    emits:['success'],
    components: {
      sellNumDialog : defineAsyncComponent(() =>
              import('../../planManagement/signedPlan/add/modules/sellNumDialog.vue')
      ),
      fromDialog : defineAsyncComponent(
              () => import('../customer/modules/fromDialog.vue')
      ),
      chanceTaskDialog : defineAsyncComponent(
              () => import('./chanceTaskDialog.vue')
      )
    },
    setup(props, { emit }) {
      const validateMinSale = async(rule, value, callback) => {
        if (value === '' || value == 0 || !value) {
          callback('请输入最低销量')
        } else {
          callback()
        }
      }
      const validatePrice = async(rule, value, callback) => {
        if (value === '') {
          callback('请输入交易价')
        } else {
          if ( value == 0){
            callback('请输入交易价')
          }else{
            callback()
          }

        }
      }
      const currentInstance = getCurrentInstance()
      const api = inject('api')
      const userInfo = crmStore.getters['user/userInfo']
      var data = reactive({
        dialogShow: false,
        formData: {
          agentType: 'agent',
          agentId: '',
          agentName:'',
          productId: '',
          productPopularName: '',
          productName: '',
          packSpecs: '',
          terminalType: '',
          agentAttribute: '',
          areas: [],
          region: [],
          headId: '',
          headName: '',
          abstract: '',
          remark: '',
          tradePrice: '',
          agentEndTime: '',
          minSale: '',
          minSaleUnit: '1', // 最低销量单位
          isIncrease: '1',
          increaseNum: '',
          minSalePromise: '',
          planInfoDetailId:'',
          planId:0,
          planName:'',
          allocationAgentId:0,
          saleTaskId:'',
          saleTaskNo:'',
        },
        citys: [],
        agents: [],
        disabled: false,
        cascader: null,
        headOptions: crmStore.getters['company/getHeadOptions'],
        sellNumDialog: null,
        type: 1,
        isPlan: false,
        refForm: false,
        isFirst: false,
        isNot:false,
        planOptions:[],
        fromDialog:null,
        productPrices:[],
        isUnde:false,
        guidingPrice:'',
        sellerTaskRef:null,
        chanceTask:null,
        refInput:null,
      })
      const rule = {
        agentName: [{ required: true, message: '请选择代理商', trigger: 'change' }],
        productPopularName: [
          { required: true, message: '请选择产品', trigger: 'change' },
        ],
        terminalType: [
          { required: true, message: '请选择营销终端', trigger: 'change' },
        ],
        agentAttribute: [
          {
            required: true,
            message:
                    data.formData.agentType == 'agent'
                            ? '请选择代理属性'
                            : '请选择兼职属性',
            trigger: 'change',
          },
        ],
        areas: [{ required: true, message: '请选择代理地区', trigger: 'change' }],
        agentEndTime: [
          {
            type: 'date',
            required: true,
            message:'请选择代理期限至',
            trigger: 'change',
          },
        ],
        tradePrice: [
          { required: true, validator:validatePrice, trigger: 'blur' },
        ],
        minSale: [{ required: true, validator: validateMinSale }],
        minSalePromise: [
          { required: true, message: '请输入销量保证金', trigger: 'blur' },
        ],
        headId: [
          { required: true, message: '请选择营销职员', trigger: 'change' },
        ],
      }
      const props1 = reactive({
        multiple: true,
        expandTrigger: 'hover',
        label: 'regionName',
        value: 'regionCode',
      })
      const unitOptions =
              crmStore.getters['dictionary/getDictionary']['sell_num_unit']
      const appOptions = crmStore.getters['dictionary/getDictionary']['app_mode']
      const attributeOptions =
              crmStore.getters['dictionary/getDictionary']['agent']
      const personOptions =
              crmStore.getters['dictionary/getDictionary']['agent_person']


      const productConfirm = (val) => {
        data.formData.productId = val.id
        data.formData.productPopularName = val.productPopularName
        data.formData.productName = val.productName
        data.formData.approvalNumber = val.approvalNumber
        data.formData.packSpecs = val.packSpecs
        data.formData.producer = val.producer
        data.formData.sellUnit = val.sellUnit

        getArea()
        data.formData.areas = []
        data.formData.region = []
        getProductPrice()
      }

      const getProductPrice = () => {
        data.productPrices = []
        data.isUnde = false
        if (data.formData.region.length && data.formData.productId && data.formData.terminalType){
          api.signedAgent.PRODUCT_PRICE_STRATEGY_MIN_PRICE({productId:data.formData.productId,region:data.formData.region,terminalType:data.formData.terminalType}).then(res=>{
            if (!res.code){
              data.productPrices = res.data.list || []
              if (data.formData.tradePrice){
                onBlur()
              }
            }else {
              currentInstance.proxy.customMessage({type:'error',message:res.msg})
            }
          })
        }
      }

      const onBlur = () => {
        data.isUnde = false
        if (data.productPrices && data.productPrices.length && data.formData.tradePrice){
          data.isUnde = true
          for (let i = 0; i < data.productPrices.length; i++) {
            data.guidingPrice = data.productPrices[i].guidingPrice
            if (data.formData.tradePrice >= data.productPrices[i].guidingPrice){
              data.isUnde = false
              break
            }
          }
        }
      }

      const typeChange = () => {
        getProductPrice()
      }

      const areaChange = (val) => {
        const serve = currentInstance.proxy.getServeAreaData(
                val,
                data.cascader.getCheckedNodes()
        )
        data.formData.region = serve

        getProductPrice()
      }

      const attributeChange = () => {
        getArea()

        data.formData.areas = []
        data.formData.region = []
      }

      const headChange = () => {
        const index = data.headOptions.findIndex(
                (a) => a.id == data.formData.headId
        )
        if (index != -1) {
          data.formData.headName = data.headOptions[index].realName
        }
        data.formData.planInfoDetailId = ''
        getPlanDetail()
      }

      const getPlanDetail = () => {
        let a = {
          listType:'1',
          planType:'2',
          page:1,
          pageSize:100,
          status:'4',
          headId:data.formData.headId,
        }

        api.plan.PLAN_DETAIL_LIST(a).then(res=>{
          if (!res.code){
            data.planOptions = res.data.list || [];
            data.planOptions.forEach(item=>{
              item.id = item.planDetail.id
              item.name = item.planDetail?.productPopularName + "-" + (item.planDetail?.areaName ? item.planDetail?.cityName + "/" + item.planDetail?.areaName : item.planDetail?.cityName ? item.planDetail?.cityName : item.planDetail?.provinceName)
            })
          }else {
            currentInstance.proxy.customMessage({type:'error',message:res.msg})
          }
        })
      }

      const sellerFocus = () => {
        data.sellerTaskRef.openPopover();
      }

      const sellerClear = () => {
        data.formData.planInfoDetailId = 0
        data.formData.planName = ''
        data.isPlan = false
      }

      const sellerConfirm = (item) => {
        data.isPlan = true
        data.formData.planInfoDetailId = item.planDetail.id
        data.formData.planId = item.planInfo.id
        data.formData.planName = item.planInfo.planName
        data.formData.productId = item.planInfo.productId
        data.formData.productPopularName = item.planInfo.productPopularName
        data.formData.productName = item.planInfo.productName
        data.formData.packSpecs = item.planInfo.packSpecs
        data.formData.producer = item.planInfo.producer
        data.formData.sellUnit = item.planInfo.sellUnit

        data.formData.headId = item.allocationAgent.headId
        data.formData.headName = item.allocationAgent.headName
        // data.formData.agentId = item.allocationAgent.agentId
        // data.formData.agentType = item.allocationAgent.agentType
        if (item.planInfo.terminalType) {
          data.formData.terminalType = item.planInfo.terminalType
        }
        data.formData.minSale = item.planDetail.minSale
        data.formData.minSaleUnit = item.planDetail.minSaleUnit
        data.formData.isIncrease = item.planDetail.isIncrease
        data.formData.increaseNum = item.planDetail.increaseNum
        data.formData.minSalePromise = item.planDetail.sellEarnestMoney
        let arr = []
        if (item.planInfo.planType == 2) {
          if (item.planDetail.provinceCode) {
            arr.push(item.planDetail.provinceCode)
          }
          if (item.planDetail.cityCode) {
            arr.push(item.planDetail.cityCode)
          }
          if (item.planDetail.areaCode) {
            arr.push(item.planDetail.areaCode)
          }
        } else {
          arr = [
            item.planDetail.terminalProvince,
            item.planDetail.terminalCity,
            item.planDetail.terminalArea,
          ]
        }

        data.formData.areas = []
        data.formData.region = []
        let agents = []
        if (item.allocationAgent.allocationAgentDetails){
          item.allocationAgent.allocationAgentDetails.forEach(a => {
            a.id = a.agentId
            a.userName = a.agentName
            agents.push(a)
          })
          data.agents = agents
        }

        getArea()
      }

      const taskConfirm = (val) => {
        data.isPlan = true
        data.formData.allocationAgentId = val.id
        data.formData.saleTaskId = val.saleTaskId
        data.formData.saleTaskNo = val.taskNo

        data.formData.productId = val.productId
        data.formData.productPopularName = val.productPopularName
        data.formData.productName = val.productName
        data.formData.packSpecs = val.packSpecs
        data.formData.producer = val.producer
        data.formData.sellUnit = val.sellUnit

        if (val.relationData){
          let item = JSON.parse(val.relationData)

          data.formData.minSale = item.planDetail.minSale
          data.formData.minSaleUnit = item.planDetail.minSaleUnit
          data.formData.isIncrease = item.planDetail.isIncrease
          data.formData.increaseNum = item.planDetail.increaseNum
          data.formData.minSalePromise = item.planDetail.sellEarnestMoney
        }

        getArea()
      }

      const taskBlur = () => {

      }

      const taskFocus = () => {
        // data.chancePop.openPopover()
        data.chanceTask.openDialog()
        data.refInput.blur()
      }

      const taskClear = () => {
        data.isPlan = false
        data.formData.allocationAgentId = 0
        data.formData.saleTaskNo = ''
        data.formData.saleTaskId = ''
      }

      const planChange = (val) => {
        let index = data.planOptions.findIndex(a=>a.id == val)
        if (index != -1){
          let item = data.planOptions[index]
          data.isPlan = true
          data.formData.productId = item.planInfo.productId
          data.formData.productPopularName = item.planInfo.productPopularName
          data.formData.productName = item.planInfo.productName
          data.formData.packSpecs = item.planInfo.packSpecs
          data.formData.producer = item.planInfo.producer
          data.formData.sellUnit = item.planInfo.sellUnit

          data.formData.headId = item.allocationAgent.headId
          data.formData.headName = item.allocationAgent.headName
          // data.formData.agentId = item.allocationAgent.agentId
          // data.formData.agentType = item.allocationAgent.agentType
          if (item.planInfo.terminalType) {
            data.formData.terminalType = item.planInfo.terminalType
          }
          data.formData.minSale = item.planDetail.minSale
          data.formData.minSaleUnit = item.planDetail.minSaleUnit
          data.formData.isIncrease = item.planDetail.isIncrease
          data.formData.increaseNum = item.planDetail.increaseNum
          data.formData.minSalePromise = item.planDetail.sellEarnestMoney
          let arr = []
          if (item.planInfo.planType == 2) {
            if (item.planDetail.provinceCode) {
              arr.push(item.planDetail.provinceCode)
            }
            if (item.planDetail.cityCode) {
              arr.push(item.planDetail.cityCode)
            }
            if (item.planDetail.areaCode) {
              arr.push(item.planDetail.areaCode)
            }
          } else {
            arr = [
              item.planDetail.terminalProvince,
              item.planDetail.terminalCity,
              item.planDetail.terminalArea,
            ]
          }

          data.formData.areas = []
          data.formData.region = []
          let agents = []
          if (item.allocationAgent.allocationAgentDetails){
            item.allocationAgent.allocationAgentDetails.forEach(a => {
              a.id = a.agentId
              a.userName = a.agentName
              agents.push(a)
            })
            data.agents = agents
          }


          getArea()
        }else {
          data.isPlan = false
        }

      }

      const editNum = () => {
        data.sellNumDialog.open(data.formData)
      }

      const close = () => {
        data.disabled = true
        data.formData = {
          agentType: 'agent',
          agentId: '',
          agentName:'',
          productId: '',
          productPopularName: '',
          productName: '',
          packSpecs: '',
          terminalType: '',
          agentAttribute: '1',
          areas: [],
          region: [],
          headId: '',
          abstract: '',
          remark: '',
          tradePrice: '',
          agentEndTime: '',
          minSale: '',
          minSaleUnit: '1', // 最低销量单位
          isIncrease: '1',
          increaseNum: '',
          minSalePromise: '',
          planInfoDetailId:'',
          planId:0,
          planName:'',
          allocationAgentId:0,
          saleTaskNo:'',
          saleTaskId: '',
        }
        data.isPlan = false
        data.agents = []
        data.planOptions = []
        data.refForm.clearValidate()
        data.dialogShow = false
      }

      const confirm = () => {
        console.log(data.formData.minSale)
        data.refForm.validate((val) => {
          if (val) {
            data.formData.minSale = Number(data.formData.minSale)
            data.formData.tradePrice = Number(data.formData.tradePrice)
            data.formData.minSalePromise = Number(data.formData.minSalePromise)
            data.formData.increaseNum = Number(data.formData.increaseNum)
            data.formData.planInfoDetailId = Number(data.formData.planInfoDetailId)
            data.formData.saleTaskId = Number(data.formData.saleTaskId)
            if (data.formData.id) {
              // api.signedAgent
              //     .AGENT_PRODUCT_EDIT(data.formData)
              //     .then((res) => {
              //         if (!res.code) {
              //             currentInstance.proxy.customMessage({
              //                 type: 'success',
              //                 message: '编辑成功',
              //             })
              //             emit('success')
              //
              //             handleClose()
              //         } else {
              //             currentInstance.proxy.customMessage({
              //                 type: 'error',
              //                 message: res.msg,
              //             })
              //             data.disabled = false
              //         }
              //     })
              //     .catch((err) => {
              //         data.disabled = false
              //     })
            } else {
              api.signedAgent
                      .AGENT_PRODUCT_CREATE(data.formData)
                      .then((res) => {
                        if (!res.code) {
                          currentInstance.proxy.customMessage({
                            type: 'success',
                            message: '添加成功',
                          })
                          emit('success')

                          close()
                        } else {
                          currentInstance.proxy.customMessage({
                            type: 'error',
                            message: res.msg,
                          })
                        }
                      })
                      .catch((err) => {})
            }
          }
        })
      }

      const open = (type, item) => {
        data.disabled = true
        data.formData.headId = userInfo.ID
        data.formData.headName = userInfo.realName
        getPlanDetail()
        if (item) {
          data.formData.productId = item.productId
          data.formData.productPopularName = item.productPopularName
          data.formData.productName = item.productName
          data.formData.packSpecs = item.packSpecs
          data.formData.producer = item.producer
          data.formData.sellUnit = item.sellUnit

          data.formData.agentId = item.objectId
          data.formData.agentName = item.objectName
        }
        data.formData.agentAttribute = type + ''
        data.type = type
        data.dialogShow = true
        setTimeout(()=>{
          data.disabled = false
        },500)

        getArea()
      }

      const getArea = () => {
        if (data.formData.productId && data.formData.agentAttribute) {
          const pam = {
            productId: data.formData.productId,
            agentAttribute: data.formData.agentAttribute,
          }
          api.signedAgent
                  .AGENT_PRODUCT_REGION(pam)
                  .then((res) => {
                    if (!res.code && res.data) {
                      data.citys = res.data.region
                      // if (data.isFirst) {
                      //   checkArea()
                      // }
                    }
                  })
                  .catch()
        }
      }

      const checkArea = () => {
        data.isFirst = false
        let bo = true
        let arr = JSON.parse(JSON.stringify(data.citys))
        if (!data.formData.areas[0]) return
        const aa = data.formData.areas[0]
        for (let i = 0; i < aa.length; i++) {
          const code = aa[i]
          const index = arr.findIndex((a) => a.regionCode == code)
          if (index != -1) {
            const pos = arr[index]
            if (pos.disabled) {
              bo = false
              break
            }
            if (pos.children && i != aa.length - 1) {
              arr = pos.children
            }
          } else {
            bo = false
            break
          }
        }

        if (bo) {
          setTimeout(() => {
            const serve = currentInstance.proxy.getServeAreaData(
                    data.formData.areas,
                    data.cascader.getCheckedNodes()
            )
            data.formData.region = serve
          }, 500)
        } else {
          data.formData.areas = []
        }
      }

      // 获取代理商列表
      const querySearchAsyncAgent = async(queryString, cb) => {
        if (!queryString){
          data.isNot = false
          cb(data.agents)
        }else {
          const a = {
            keyWord: queryString,
          }
          let results = []
          const res = await api.editorial.EDITORIAL_KEYWORDS(a)
          if (!res.code && res.data) {
            results = res.data.list || []
            if ((!res.data.list || !res.data.list.length) && queryString){
              data.isNot = true
            }else {
              data.isNot = false
            }
          }
          cb(results)
        }
      }

      const agentBlur = () => {
        if (!data.formData.agentId){
          data.formData.agentName = ''
        }
      }

      // 代理商事件
      const handleSelectAgent = (val) => {
        data.formData.agentId = val.id
        data.formData.agentName = val.agentName
        data.formData.agentType = val.agentType
        if (val.agentType != 'agent'){
          data.formData.agentName = val.userName
        }
      }

      const disabledDate = (time) => {
        return !(time.getTime() > Date.now())
      }

      const onCreate = () => {
        data.fromDialog.open()
      }

      watch(
        ()=>data.formData.minSale,
        (newVal,oldval)=>{
          if(newVal){
            nextTick(()=>{
              data.refForm.clearValidate('minSale')
            })
          }
        },
        {immediate: true}
      )

      onMounted(() => {

      })

      return {
        ...toRefs(data),
        rule,
        appOptions,
        attributeOptions,
        personOptions,
        props1,
        unitOptions,

        close,
        confirm,
        open,
        productConfirm,
        areaChange,
        headChange,
        attributeChange,
        disabledDate,
        editNum,
        onCreate,
        querySearchAsyncAgent,
        handleSelectAgent,
        planChange,
        onBlur,
        typeChange,
        sellerConfirm,
        sellerClear,
        sellerFocus,
        taskBlur,
        taskFocus,
        taskClear,
        taskConfirm,
        agentBlur,
      }
    },
  })
</script>

<style scoped>
</style>
